package com.handpay.zztong.hp.qualification.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.ui.QuailficationPhotoView;
import com.handpay.framework.ui.QuailficationPhotoView.UploadClickListener;
import com.handpay.framework.utils.BitmapLoader;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.MyAsyncTask;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.qualification.model.MerchantPicPreviewBean;
import com.handpay.zztong.hp.qualification.model.PicPreviewInfo;
import com.handpay.zztong.hp.ui.QualificationGridView;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.BitmapZipUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.Hashtable;
import java.util.List;
import java.util.zip.CRC32;

import se.krka.kahlua.vm.LuaTable;


public class T0QualificationActivity extends ZZTongActivity {
    private QualificationGridView gridView;
    private PicPreviewInfo[] pData = new PicPreviewInfo[9];
    private MyBaseAdapter myAdapter;
    private QuailficationPhotoView pView;
    private int position = 0;
    private Uri mPicUri;
    private int TAKE_PICTURE = 1;
    private MyAsyncTask<PicPreviewInfo, Integer, Integer> mTask;

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.tilte_qualification), true);
    }

    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_CAMERA) {
            Toast.makeText(T0QualificationActivity.this, R.string.message_camera_succesed, Toast.LENGTH_SHORT).show();
        }
    }

    //获取已经上传到额预览图片
    private void getQualificationpic() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("channel", ClientEngine.CHANNEL);
        doJsonPost(this, Do_getMerchantPicPreview, MerchantPicPreviewBean.class, params);
    }

    /**
     * 上传图片
     *
     * @param url    图片路径
     * @param mCrc32 orc32
     * @return 返回是否成功
     */
    private boolean uploadQualificationPicWithJSON(String url, CRC32 mCrc32) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("channel", ClientEngine.CHANNEL);
        String hex = "";
        String imgCheck = "";
        byte[] imgByte = null;
//        Bitmap bitmap=null;
//		if (BitmapLoader.isHttpUrl(url)) {
//			imgByte = BitmapLoader.getInstance(T0QualificationActivity.this)
//					.loadBitmapNoCompress(url);
//		} else {
//			bitmap = BitmapLoader.getInstance(T0QualificationActivity.this)
//					.loadBitmap(url, url);
//			imgByte = CommonUtils.getBitmapBytes(bitmap, ZZTConstant.MAXBYTE);
//		}
        imgByte = BitmapZipUtils.getCatBitmap(url, 480, 800, 200);
        Log.i("result", "压缩后大小：" + imgByte.length / 1024 + "kb");
//		HPLog.i(HPLog.LFP_TAG, "压缩前图片字节长度:"+imgByte.length);
//		Bitmap newBitmap = doCropImage(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length));
//		imgByte = BitmapUtil.Bitmap2BytesCrop(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length));
//		imgByte=CommonUtils.getBitmapBytes(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length), 200);
//		HPLog.i(HPLog.LFP_TAG, "压缩后图片字节长度:"+imgByte.length);
        imgCheck = CommonUtils.getCRC(mCrc32, imgByte);
//		HPLog.i(HPLog.LFP_TAG, "imgCheck:"+imgCheck);
        params.put("picCheck", imgCheck);
        ResponseBean responseBean;
        if (ZZTConfig.UPLOAD_BIN) {
            // 传二进制数据到后台
            responseBean = HttpSFTConnector.uploadPic2ServerWithJson(T0QualificationActivity.this, ResponseBean.class, Do_uploadMerchantPic, params, imgByte);
        }
        if (!TextUtils.isEmpty((responseBean.getErrMessage())) && !TextUtils.isEmpty(responseBean.getResponseCode())) {
            if ("99".equals(responseBean.getResponseCode())) {
                this.showAlertDialog(this, getString(R.string.prompt), responseBean.getErrMessage(), false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitAccount();
                        dialog.dismiss();
                    }
                });
                return false;
            } else if ("999".equals(responseBean.getResponseCode())) {
                showAlertDialog(this, getString(R.string.offline_notify_txt), responseBean.getErrMessage(), false, getString(R.string.tv_exit), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitapp();
                        dialog.dismiss();
                    }
                }, getString(R.string.tv_relogin), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitAccount();
                        dialog.dismiss();
                    }
                });
                return false;
            }
            return false;
        }
        return true;
    }

    //上传图片
    private boolean uploadQualificationPic(String url, CRC32 mCrc32) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        Hashtable<String, Object> resp;
        params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("channel", ClientEngine.CHANNEL);
        String hex = "";
        String imgCheck = "";
        byte[] imgByte = null;
//		Bitmap bitmap=null;
//		if (BitmapLoader.isHttpUrl(url)) {
//			imgByte = BitmapLoader.getInstance(T0QualificationActivity.this)
//					.loadBitmapNoCompress(url);
//		} else {
//			bitmap = BitmapLoader.getInstance(T0QualificationActivity.this)
//					.loadBitmap(url, url);
//			imgByte = CommonUtils.getBitmapBytes(bitmap, ZZTConstant.MAXBYTE);
//		}
        imgByte = BitmapZipUtils.getCatBitmap(url, 480, 800, 200);
        Log.i("result", "压缩后大小：" + imgByte.length / 1024 + "kb");
//		HPLog.i(HPLog.LFP_TAG, "压缩前图片字节长度:"+imgByte.length);
//		Bitmap newBitmap = doCropImage(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length));
//		imgByte = BitmapUtil.Bitmap2BytesCrop(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length));
//		imgByte=CommonUtils.getBitmapBytes(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length), 200);
//		HPLog.i(HPLog.LFP_TAG, "压缩后图片字节长度:"+imgByte.length);
        imgCheck = CommonUtils.getCRC(mCrc32, imgByte);
//		HPLog.i(HPLog.LFP_TAG, "imgCheck:"+imgCheck);
        params.put("picCheck", imgCheck);
        if (ZZTConfig.UPLOAD_BIN) {
            // 传二进制数据到后台
            resp = HttpSFTConnector.uploadPic2Server(T0QualificationActivity.this, Do_uploadMerchantPic, params, imgByte);
        }
//		else {
//			// 传HEX str到后台
//			hex = CommonUtils.bytesToHexString(imgByte);
//			if (TextUtils.isEmpty(hex)) {
//				// outOfMemory 返回上传失败。
//				return false;
//			}
//			params.put("pic",hex);
//			doPost(this, Do_uploadMerchantPic, params);
//		}
        int respCode = (Integer) resp.get(HttpEngine.Key_RespCode);
        String errMsg = (String) resp.get(HttpEngine.Key_RespErrMsg);
        if (respCode < 0 || !TextUtils.isEmpty(errMsg)) {
            return false;
        }
        byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
        if (data == null) {
            return false;
        }
        LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, false);
        if (luaTable == null) {
            return false;
        }
        String em = (String) luaTable.rawget("errMessage");
        HPLog.i(HPLog.LFP_TAG, "em:" + em);
        if (!TextUtils.isEmpty(em)) {
            dealWithLoginTimeOut(resp);
            return false;
        }
        return true;
    }

    //删除服务器的图片
    private void deletePic(String picid) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("picId", picid);
        doPost(this, Do_deleteMerchantPicById, params, true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_qualification);
        super.onCreate(savedInstanceState);
        //如果没有相机权限则去获取相机权限
        checkPermission();
        getQualificationpic();
        initView();
    }

    /**
     * 检测权限
     */
    private void checkPermission() {
        if (!AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
            Toast.makeText(this, R.string.message_camera_failed, Toast.LENGTH_SHORT).show();
            AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_CAMERA).
                    permission(Manifest.permission.CAMERA).
                    rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            AndPermission.rationaleDialog(T0QualificationActivity.this, rationale).show();
                        }
                    }).send();
        }
    }

    private void initView() {
        findViewById(R.id.upLoadPic).setOnClickListener(this);
        gridView = (QualificationGridView) findViewById(R.id.myGridView);
        myAdapter = new MyBaseAdapter(this);
        gridView.setAdapter(myAdapter);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.upLoadPic) {
            if (isCanUpload()) {
                doUpload();
            } else {
                Toast.makeText(this, R.string.updload_newimg, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        if (super.netJsonResponse(action, resp, showAlert)) return true;
        if (ZZTongActivity.Do_getMerchantPicPreview.equals(action)) {
            MerchantPicPreviewBean merchantPicPreviewBean = (MerchantPicPreviewBean) resp;
            HPLog.i(HPLog.LFP_TAG, "merchantPicPreviewBean=" + merchantPicPreviewBean.toString());
            //这里需要注意，由于后台服务器不知什么原因，可能返回大于9个图片，大于9个切断
            int dataSize=merchantPicPreviewBean.getList().size();
            PicPreviewInfo[] picPreviewInfos = new PicPreviewInfo[dataSize>pData.length?pData.length:dataSize];
            for (int i = 0; i < merchantPicPreviewBean.getList().size(); i++) {
                if (i == pData.length) {
                    break;
                }
                MerchantPicPreviewBean.ListBean picPreviewBean = merchantPicPreviewBean.getList().get(i);
                if (picPreviewBean != null) {
                    PicPreviewInfo picPreviewInfo = new PicPreviewInfo(picPreviewBean.getPicId(), picPreviewBean.getPicUrl());
                    picPreviewInfos[i] = picPreviewInfo;
                }

            }
            if (picPreviewInfos.length > 0) {
                System.arraycopy(picPreviewInfos, 0, this.pData, 0, picPreviewInfos.length);
                for (int j = picPreviewInfos.length; j < pData.length; j++) {
                    this.pData[j] = null;
                }
            }
            myAdapter.notifyDataSetChanged();
        }
        return false;
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert, OnClickListener on) {
        this.closeProgressDialog();
        if (ZZTongActivity.Do_getMerchantPicPreview.equals(action)) {
            HPLog.i(HPLog.LFP_TAG, "Do_getMerchantPicPreview");
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            if (luaTable != null) {
                int items = CommonUtils.objectToInt(luaTable.rawget("items"));
                HPLog.i(HPLog.LFP_TAG, "items=" + items);
                PicPreviewInfo[] Data = PicPreviewInfo.getPicPreviewsArray(luaTable, items);
                if (Data != null && Data.length > 0) {
                    for (int i = 0; i < Data.length; i++) {
                        this.pData[i] = Data[i];
                    }
                    for (int j = Data.length; j < pData.length; j++) {
                        this.pData[j] = null;
                    }
                }
                myAdapter.notifyDataSetChanged();
            }
        } else if (ZZTongActivity.Do_deleteMerchantPicById.equals(action)) {
            HPLog.i(HPLog.LFP_TAG, "Do_deleteMerchantPicById");
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            if (luaTable != null) {
                HPLog.i(HPLog.LFP_TAG, "luaTable!=null");
//				Object  obj=luaTable.rawget("responseCode");
//				if(obj!=null&&obj instanceof Integer){
//					
//				}else if(obj!=null && obj instanceof Double){
//					
//				}
                String em = (String) luaTable.rawget("errMessage");
                if (em != null && em.length() > 0) {
                    Toast.makeText(this, em, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "删除成功！", Toast.LENGTH_SHORT).show();
                }
            }
        }
        return false;
    }

    private void doUpload() {
        HPLog.i("time", "doUpload:" + SystemClock.elapsedRealtime());
        cancelTask();
        //检测网络，如果网络不可用，提示打开网络
        if (checkNetAndAlert(this)) {
            return;
        }
        //分别上传四、五张照片。最后发送提交.如果其中有一个发送失败。提示用户发送失败，请重新提交。
        //返回值。0表示成功，1表示失败，2，表示用户取消
        mTask = new MyAsyncTask<PicPreviewInfo, Integer, Integer>() {


            @Override
            protected void onPreExecute() {

//                T0QualificationActivity.this.showProgressDialog();
//                progressDialog = new ProgressDialog(T0QualificationActivity.this);
//                progressDialog.setMessage(getString(R.string.uploading_template, ""));
//                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//                progressDialog.setCancelable(false);
//                progressDialog.show();

                showProgressDialog(T0QualificationActivity.this, getString(R.string.uploading_template, ""));
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Integer result) {

//                closeProgressDialog();
                if (0 == result) {
                    //***********
                    T0QualificationActivity.this.getQualificationpic();

                    //成功以后，删除图片
                    CommonUtils.removePics();
                    //***********
                    showAlertDialog(T0QualificationActivity.this, R.string.tip, R.string.img_upload_su);
                    //***********
//					Log.i("result", "图片上传成功！");
                } else if (1 == result) {
                    //上传失败
                    showAlertDialog(T0QualificationActivity.this, R.string.upload_failed, R.string.img_upload_su);
//                    Toast.makeText(T0QualificationActivity.this, R.string.upload_failed, Toast.LENGTH_SHORT).show();
                } else if (2 == result) {
                    showAlertDialog(T0QualificationActivity.this, R.string.upload_cancel, R.string.img_upload_su);
                    //上传取消
//                    Toast.makeText(T0QualificationActivity.this, R.string.upload_cancel, Toast.LENGTH_LONG).show();
                }
                super.onPostExecute(result);
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                HPLog.i(HPLog.YL_TAG, "onProgressUpdate 1aaa:" + getString(R.string.uploaded_template, values[0]));
//                if (null != progressDialog) {
//                    HPLog.i(HPLog.YL_TAG,"onProgressUpdate 2:"+values[0]);
//                    progressDialog.setMessage(getString(R.string.uploaded_template, values[0]));
//                }
//                super.onProgressUpdate(values);
                setProgressDialogMessage(getString(R.string.uploaded_template, values[0]));
//                setProgressDialogMessage("aaaaaaaaa");
            }

            @Override
            protected void onCancelled(Integer result) {

//                closeProgressDialog();
                //上传取消
                Toast.makeText(T0QualificationActivity.this, R.string.upload_cancel, Toast.LENGTH_SHORT).show();
                super.onCancelled();
            }

            @Override
            protected Integer doInBackground(PicPreviewInfo... params) {
                CRC32 mCrc32 = new CRC32();
                int j = 0;
                for (int i = 0; i < pData.length; i++) {
                    if (null != pData[i] && !BitmapLoader.isHttpUrl(pData[i].picUrl)) {
                        if (uploadQualificationPicWithJSON(pData[i].picUrl, mCrc32)) {
                            j++;
                            this.publishProgress(j);
                        } else {
                            return 1;
                        }
                    }
                }
                if (this.isCancelled()) {
                    return 2;
                }
                return 0;
            }
        };
        mTask.execute();
    }

    private void cancelTask() {
        //当该activity不可见的时候，取消上传任务。
        if (null != mTask) {
            HPLog.i("ssss", "cancel task");
            mTask.cancel(true);
            mTask = null;
        }
    }

    public class MyBaseAdapter extends BaseAdapter implements UploadClickListener {
        LayoutInflater inflater;
        Context myContext;

        public MyBaseAdapter(Context context) {
            super();
            myContext = context;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {

            return pData.length;
        }

        @Override
        public Object getItem(int position) {
            return pData[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.quailification_pic_item, null);
                holder = new ViewHolder();
                holder.photoView = (QuailficationPhotoView) convertView.findViewById(R.id.photoView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (parent.getChildCount() == position) {
                Log.i("result", "position=" + position);
                PicPreviewInfo obj = pData[position];
                String fileUrl = null;
                if (obj != null && !TextUtils.isEmpty(obj.picUrl)) {
                    fileUrl = obj.picUrl;
                } else {
                    holder.photoView.setmOutputFileUri(null);
                }
                holder.photoView.init(fileUrl, true, this);
                holder.photoView.setPosition(position);
            }
            return convertView;
        }

        @Override
        public void onUploadClickListener(QuailficationPhotoView view) {
            if (AndPermission.hasPermission(T0QualificationActivity.this, Manifest.permission.CAMERA)) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                mPicUri = CommonUtils.randomUri(CommonUtils.getAccessDir());
                HPLog.i("shuai", "create random uri -----------" + mPicUri);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicUri);
                position = view.getPosition();
                pView = view;
                startActivityForResult(intent, TAKE_PICTURE);
            } else {
                checkPermission();
            }
        }

        @Override
        public void onDelectClickListener(final QuailficationPhotoView view) {
            T0QualificationActivity.this.showAlertDialog(T0QualificationActivity.this, getResources().getString(R.string.tip), getResources().getString(R.string.text_delete_msg), false, getResources().getString(R.string.text_delete_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (null != pData[view.getPosition()]) {
                        //是网络地址则是从服务器获取的已拍照图片
//						if(pData[view.getPosition()].picUrl.length()>0){
//							if(null!=pData[view.getPosition()].picId){
//								deletePic(pData[view.getPosition()].picId);
//							}
//						}else{
                        try {
                            File temp = new File(pData[view.getPosition()].picUrl);
                            if (temp.exists()) {
                                temp.delete();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    pData[view.getPosition()] = null;
                    view.deleteView();
//					}
                    dialog.dismiss();
                }
            }, getResources().getString(R.string.text_delete_cancel), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode && requestCode == TAKE_PICTURE) {
            if (mPicUri != null) {
                String uri = mPicUri.toString();
                HPLog.i(HPLog.LFP_TAG, "uri=" + uri);
                if (pData[position] == null) {
                    pData[position] = new PicPreviewInfo(uri);
                } else {
                    pData[position].picUrl = uri;
                }
                pView.setPic(uri);
            }
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_CAMERA) {
            checkPermission();
        }
        myAdapter.notifyDataSetChanged();
        // 控制程序调用相机的时候，不去发版本检测协议。
        ZZTConfig.isActive = false;
        HPLog.e("shuai", "ZZTConfig.isActive: " + ZZTConfig.isActive);
        mPicUri = null;
    }

    /**
     * ViewHolder类
     */
    static class ViewHolder {
        QuailficationPhotoView photoView;
    }


    private boolean isCanUpload() {
        for (PicPreviewInfo data : pData) {
            if (data != null && data.picUrl != null && data.picUrl.length() > 0 && data.picUrl.contains("file:")) {
                return true;
            }
        }
        return false;
    }
}
